package com.my.study.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class MySource {

    private volatile boolean FLAG = true;

    private AtomicInteger atomicInteger = new AtomicInteger();

    private BlockingQueue<String> blockingDeque = null;

    public MySource(BlockingQueue<String> deque) {
        this.blockingDeque = deque;
        log.info(">>>>>>>>>>>>>>>>>>>>>" + deque.getClass().getName());
    }

    public void myProd(String data) {
        try {
            String newData;
            boolean result;
            while (FLAG) {
                newData = data + atomicInteger.getAndIncrement();
                result = blockingDeque.offer(newData, 2L, TimeUnit.SECONDS);
                if (result) {
                    log.info(Thread.currentThread().getName() + ">>>>>>>>>>>>>>>>>>>>>生产成功:" + newData);
                } else {
                    log.info(Thread.currentThread().getName() + ">>>>>>>>>>>>>>>>>>>>>生产失败:" + newData);
                }
                TimeUnit.SECONDS.sleep(1);
            }
            log.info(">>>>>>>>>>>>>>>>>>>>>main线程发起停止生产,生产退出");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(">>>>>>>>>>>>>>>>>>>>>生产者生产异常");
        }
    }

    public void myConsumer() {
        try {
            String result;
            while (FLAG) {
                result = blockingDeque.poll(2L, TimeUnit.SECONDS);
                if (result == null || "".equals(result)) {
                    log.info(Thread.currentThread().getName() + ">>>>>>>>>>>>>>>>>>>>>获取不到值,消费退出");
                    FLAG = false;
                } else {
                    log.info(Thread.currentThread().getName() + ">>>>>>>>>>>>>>>>>>>>>消费成功:" + result);
                }
            }
            log.info(">>>>>>>>>>>>>>>>>>>>>main线程发起停止消费,消费退出");
        } catch (Exception e) {
            e.printStackTrace();
            log.error(">>>>>>>>>>>>>>>>>>>>>生产者生产异常");
        }
    }

    public void stop() {
        FLAG = false;
    }

}
